package com.tao.service.impl;

import com.tao.service.HotSearchService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Transactional
@Service("redisService")
public class HotSearchServiceImpl implements HotSearchService {
    //导入数据源
//    @Resource(name = "redisSearchTemplate")
    @Resource
    private StringRedisTemplate redisSearchTemplate;

    //根据history搜索其相关最热的前5名 (如果history为null空，则返回redis存储的前5最热词条)
    @Override
    public List<String> getHotList(String history) {
        String key = history;
        Long now = System.currentTimeMillis();
        List<String> result = new ArrayList<>();
        ZSetOperations zSetOperations = redisSearchTemplate.opsForZSet();
        ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue();
        Set<String> value = zSetOperations.reverseRangeByScore("title", 0, Double.MAX_VALUE);
        //key不为空的时候 推荐相关的最热前5名
        if(StringUtils.isNotEmpty(history)){
            for (String val : value) {
                if (StringUtils.containsIgnoreCase(val, key)) {
                    if (result.size() > 4) {//只返回最热的前5名
                        break;
                    }
                    Long time = Long.valueOf(valueOperations.get(val));
                    if ((now - time) < 2592000000L) {//返回最近一个月的数据
                        result.add(val);
                    } else {//时间超过一个月没搜索就把这个词热度归0
                        zSetOperations.add("title", val, 0);
                    }
                }
            }
        }else{
            for (String val : value) {
                if (result.size() > 4) {//只返回最热的前5名
                    break;
                }
                Long time = Long.valueOf(valueOperations.get("time:search:"+val));
                if ((now - time) < 2592000000L) {//返回最近一个月的数据
                    result.add(val);
                } else {//时间超过一个月没搜索就把这个词热度归0
                    zSetOperations.add("title", val, 0);
                }
            }
        }
        return result;
    }

    //每次点击给相关词searchkey热度 +1
    @Override
    public int incrementScore(String history) {
        String key = history;
        if(StringUtils.isNoneEmpty(key)){
            Long now = System.currentTimeMillis();
            ZSetOperations zSetOperations = redisSearchTemplate.opsForZSet();
            ValueOperations<String, String> valueOperations = redisSearchTemplate.opsForValue();
            zSetOperations.incrementScore("title", key, 1);
            valueOperations.getAndSet("time:search:"+key, String.valueOf(now));
        }
        return 1;
    }
}
